package com.luocc.ccdemo.common

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.luocc.ccdemo.R
import com.luocc.ccdemo.entity.Video
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer

class VideoListAdapter(context: Context) :
    ListAdapter<Video, RecyclerView.ViewHolder>(MyDiffCallback()) {

    class MyDiffCallback : DiffUtil.ItemCallback<Video>() {
        override fun areItemsTheSame(oldItem: Video, newItem: Video): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Video, newItem: Video): Boolean {
            return oldItem == newItem
        }
    }

    private val mContext: Context = context
    private var mItemClickListener: OnItemClickListener<Video>? = null
    private val mImageLoader: ImageLoader = ImageLoader.getInstance()
    private val mCoverOptions = DisplayImageOptions.Builder()
        .showImageOnLoading(R.mipmap.cover_loading)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .displayer(RoundedBitmapDisplayer(5))
        .build()
    private val mPictureOptions = DisplayImageOptions.Builder()
        .showImageOnLoading(R.mipmap.cover_loading)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .displayer(RoundedBitmapDisplayer(50))
        .build()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflate =
            LayoutInflater.from(mContext).inflate(R.layout.item_video, parent, false)
        return VideoListHolder(inflate)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = getItem(position)
        val historyCover = holder.itemView.findViewById<ImageView>(R.id.history_cover)
        val historyTitle = holder.itemView.findViewById<TextView>(R.id.history_title)
        val authorPic = holder.itemView.findViewById<ImageView>(R.id.author_pic)
        val videoAuthor = holder.itemView.findViewById<TextView>(R.id.video_author)
        historyTitle.text = item.title
        videoAuthor.text = item.username
        mImageLoader.displayImage(item.coverUrl, historyCover, mCoverOptions)
        mImageLoader.displayImage(item.userPic, authorPic, mPictureOptions)
        holder.itemView.setOnClickListener {
            mItemClickListener?.onClick(position, item)
        }
    }

    fun setOnItemClickListener(listener: OnItemClickListener<Video>) {
        mItemClickListener = listener
    }
    class VideoListHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}

